package com.android.fragmentdemo
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.pdf.PdfRenderer
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.ParcelFileDescriptor
import android.view.View
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.core.content.FileProvider
import com.android.fragmentdemo.databinding.ActivityWebviewPdfBinding
import com.android.fragmentdemo.defineviews.PDFView
import com.android.fragmentdemo.util.FileUtils
import com.hengfoxwolf.commonbase.base.BaseActivity2
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

class WebViewPdfActivity :
    BaseActivity2<ActivityWebviewPdfBinding>(ActivityWebviewPdfBinding::inflate) {

    private lateinit var fileDescriptor: ParcelFileDescriptor

    private lateinit var pdfRenderer: PdfRenderer

    private lateinit var currentPage: PdfRenderer.Page

    private var pageIndex = 0

    override fun init(savedInstanceState: Bundle?) {
        //val pdfUrl = "file:///android_asset/tech_summary.pdf"
        //loadPdfFromUrl2(pdfUrl)

        //try {
        //    openRenderer()
        //    showPage(pageIndex)
        //} catch (ex: Exception) {
        //    ex.printStackTrace()
        //}

        //openLocalPdf()

        openLocalPdf2()
    }

    override fun onStop() {
        try {
            if (View.VISIBLE == mBinding.webViewPdf.visibility) {
                closeRenderer()
            }
        } catch (ex: Exception) {
            ex.printStackTrace()
        }
        super.onStop()
    }

    override fun onBackPressed() {
        if (View.VISIBLE == mBinding.webViewPdf.visibility
            && mBinding.webViewPdf.canGoBack()) {
            mBinding.webViewPdf.goBack()
        } else {
            super.onBackPressed()
        }
    }

    private fun loadPdfFromUrl(pdfUrl: String) {
        setupWebView()
        val googleDocsUrl = "https://docs.google.com/gview?embedded=true&url=${pdfUrl}"
        mBinding.webViewPdf.loadUrl(googleDocsUrl)
    }

    private fun loadPdfFromUrl2(pdfUrl: String) {
        setupWebView()
        mBinding.webViewPdf.loadUrl(pdfUrl)
    }

    private fun setupWebView() {
        mBinding.webViewPdf.settings.apply {
            allowFileAccess = true
            domStorageEnabled = true
            builtInZoomControls = true
            displayZoomControls = true
            setSupportZoom(true)
            //javaScriptEnabled = true
        }

        mBinding.webViewPdf.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                return false
            }
        }
    }

    @Throws(IOException::class)
    private fun openRenderer() {
        //In this sample, we read a PDF from the assets directory.
        val file = File(cacheDir, FILENAME)
        if (!file.exists()) {
            //Since PdfRenderer cannot handle the compressed asset file directly, we copy it into
            //the cache directory.
            val asset = assets.open(FILENAME)
            val output = FileOutputStream(file)
            val buffer = ByteArray(1024)
            var size = asset.read(buffer)
            while (size != -1) {
                output.write(buffer, 0, size)
                size = asset.read(buffer)
            }
            asset.close()
            output.close()
        }

        fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
        //This is the PdfRenderer we use to render the PDF.
        pdfRenderer = PdfRenderer(fileDescriptor)
        currentPage = pdfRenderer.openPage(pageIndex)
    }

    @Throws(IOException::class)
    private fun closeRenderer() {
        currentPage.close()
        pdfRenderer.close()
        fileDescriptor.close()
    }

    private fun showPage(index: Int) {
        if (pdfRenderer.pageCount <= index) {
            return
        }
        //Make sure to close the current page before opening another one.
        currentPage.close()
        //Use `openPage` to open a specific page in PDF.
        currentPage = pdfRenderer.openPage(index)
        //Important: the destination bitmap must be ARGB (not RGB).
        val bitmap = Bitmap.createBitmap(currentPage.width * 3 / 2, currentPage.height, Bitmap.Config.ARGB_8888)
        //Here, we render the page onto the Bitmap.
        //To render a portion of the page, use the second and third parameter. Pass nulls to get
        //the default result.
        //Pass either RENDER_MODE_FOR_DISPLAY or RENDER_MODE_FOR_PRINT for the last parameter.
        currentPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
        // We are ready to show the Bitmap to user.
        mBinding.imageView.setImageBitmap(bitmap)
    }

    private fun openLocalPdf() {
        val pdfPath = "file:///android_asset/tech_summary.pdf"
        val pdfFile = File(pdfPath)
        val pdfUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            FileProvider.getUriForFile(this@WebViewPdfActivity, "${packageName}.fileprovider", pdfFile)
        } else {
            Uri.fromFile(pdfFile)
        }

        val pdfIntent = Intent(Intent.ACTION_VIEW)
        pdfIntent.setDataAndType(pdfUri, "application/pdf")
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

        if (packageManager.queryIntentActivities(pdfIntent, PackageManager.MATCH_ALL).size > 0) {
            startActivity(pdfIntent)
        }
    }

    private fun openLocalPdf2() {
        mBinding.pdfView.showPdfFromAssetPath(this@WebViewPdfActivity, FILENAME)

        mBinding.pdfView.setOnPageChangedListener(object : PDFView.OnPageChangedListener {
            override fun onPageChanged(currentPageIndex: Int, totalPageCount: Int) {

            }
        })
    }

    companion object {
        const val FILENAME = "tech_summary.pdf"
    }
}